package io.zhengsh.juc._1lock.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class TestHarness {

    public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (int i = 0; i < nThreads; i++) {
            Thread t = new Thread(() -> {
                try {
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }

                } catch (InterruptedException ignored) {

                }
            });
            t.start();
        }

        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        return end - start;
    }

    public static void main(String[] args) throws InterruptedException {
        TestHarness testHarness = new TestHarness();
        AtomicInteger num = new AtomicInteger(0);
        long time = testHarness.timeTasks(10, () -> System.out.println(num.incrementAndGet()));
        System.out.println("cost time: " + time + "ms");


        CountDownLatch downLatch = new CountDownLatch(1);
        downLatch.await();
        downLatch.countDown();
    }


}
